package com.mrx.compose.demo.view

import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.mrx.compose.demo.api.LoginApi.login
import com.mrx.compose.demo.model.request.UserModel
import com.mrx.compose.demo.util.UserInfoUtil
import kotlinx.coroutines.launch

object LoginView : ComposeView() {

    @Composable
    override fun showView(onRouterChanged: (String) -> Unit) {
        val userModel = UserModel(remember { mutableStateOf("admin") }, remember { mutableStateOf("admin") })
        Column(
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.fillMaxSize()
        ) {
            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(bottom = 10.dp)) {
                Text("UserName", modifier = Modifier.padding(end = 10.dp))
                OutlinedTextField(userModel.name.value, { userModel.name.value = it })
            }
            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(bottom = 10.dp)) {
                Text("PassWord", modifier = Modifier.padding(end = 10.dp))
                OutlinedTextField(userModel.password.value, { userModel.password.value = it })
            }
            Button(onClick = { login(userModel, onRouterChanged) }) { Text("Login") }
        }
    }

    private fun login(userModel: UserModel, onRouterChanged: (String) -> Unit) {
        launch {
            login(userModel).onSuccess {
                logger.info("登录结果: {}", it)
                if (it.success != true) {
                    throw IllegalStateException(it.message)
                }
                UserInfoUtil.userToken = it.data
                onRouterChanged("/home")
            }
        }
    }

}
